package com.example.suuu.project.system.controller;

import com.example.suuu.config.exception.AppException;
import com.example.suuu.model.result.ResultVo;
import com.example.suuu.tools.log.LogPrint;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@CrossOrigin
@RestController
@RequestMapping("/file")
@Api(value = "/file", tags = {"文件 API接口"})
@ApiSupport(author = "sun")
public class FileController {
    @Value("${suuu.upload}")
    private String suuuupload;
    @Value("${suuu.download}")
    private String suuudownload;

    @PostMapping("/upload")
    @LogPrint("文件上传")
    @ApiOperation(value = "文件上传",notes = "文件上传")
    public ResultVo upload(@RequestPart @RequestParam("file") MultipartFile file, HttpServletRequest req) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
        String format = sdf.format(new Date());
        File folder = new File(suuuupload + format);

        if (!folder.isDirectory()) {
            folder.mkdirs();
        }
        String oldName = file.getOriginalFilename();
        String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."), oldName.length());
        try {
            file.transferTo(new File(folder, newName));
            String filePath = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + "/imgs/" + format + newName;
            return ResultVo.ResultVoSuccess(filePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResultVo.ResultVoFail("上传失败");
    }

    @GetMapping("/download")
    @LogPrint("文件下载")
    @ApiOperation(value = "文件下载",notes = "文件下载")
    public void download(String name, HttpServletResponse response) {
        try {
            // path是指欲下载的文件的路径。
            File file = new File(suuudownload+name);
            // 取得文件名。
            String filename = file.getName();
            // 取得文件的后缀名。
            String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();
            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(suuudownload+name));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            throw new AppException("下载失败");
        }
    }
}
